package hk.cic.demointegrationapp;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.SharedPreferences;
import android.os.CountDownTimer;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.webkit.JavascriptInterface;

import com.baidu.location.BDLocation;
import com.baidu.location.BDLocationListener;
import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;
import com.cily.utils.log.BaseWv;

public class JustCheckActivity extends AppCompatActivity {
    private BaseWv wv;
    public String gps;
    public  String host;
    public  String cwrNo;
    private LocationClient locationClient = null;
    private static final int UPDATE_TIME = 500;
    private  int LOCATION_COUTNS = 0;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_just_check);

        host = getHostUrl();
        Bundle bundle = this.getIntent().getExtras();
        //接收name值
        cwrNo = bundle.getString("cwrNo");

        if (host == null || host.length() < 1){
            App.getApp().showToast("請設置服務器地址");
            return;
        }
        wv = (BaseWv)findViewById(R.id.just_check_result_id);
        wv.loadUrl("file:///android_asset/FaceCheckResult.html?host=" + host + "&cwrNo=" + cwrNo + "");
        wv.addJavascriptInterface(new JustCheckActivity.JsToJava(), "androidShare");
        wv.getSettings().setJavaScriptEnabled(true);

    }

    public int getIsIn() {
        SharedPreferences sp = getSharedPreferences("sp_setting", 0);
        return sp.getInt("is_in", 0);
    }

    private void postFaceCheckResult(String hostUrl,String cwrNO, int dutyStatus, boolean faceCheckResult, String gps,int cocationCheck) {

        int faceCheckResultInt = faceCheckResult? 1 : 0;
        wv.loadUrl("javascript:postResult('"+hostUrl+"','"+cwrNO+"','"+dutyStatus+"','"+faceCheckResultInt+"','"+gps+"','"+cocationCheck+"');");

        // 5 秒后关闭当前页
        // 倒计时
        CountDownTimer timer = new CountDownTimer(4000,1000) {
            @Override
            public void onTick(long millisUntilFinished) {
            }

            @Override
            public void onFinish() {
                finish();
            }
        };
        timer.start();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (locationClient != null && locationClient.isStarted()) {
            locationClient.stop();
            locationClient = null;
        }
    }

    @Override
    protected void onStop() {
        super.onStop();
        if (locationClient != null && locationClient.isStarted()) {
            locationClient.stop();
            locationClient = null;
        }
    }

    public String getHostUrl(){
        SharedPreferences sp = getSharedPreferences("sp_setting", 0);
        return sp.getString("server_host", "");
    }

    private void initGPS(){
        locationClient = new LocationClient(this);
        //设置定位条件
        LocationClientOption option = new LocationClientOption();
        option.setOpenGps(true);        //是否打开GPS
        option.setCoorType("bd09ll");       //设置返回值的坐标类型。
        option.setPriority(LocationClientOption.NetWorkFirst);  //设置定位优先级
        option.setProdName("LocationDemo"); //设置产品线名称。强烈建议您使用自定义的产品线名称，方便我们以后为您提供更高效准确的定位服务。
        option.setScanSpan(UPDATE_TIME);    //设置定时定位的时间间隔。单位毫秒
        locationClient.setLocOption(option);
        //注册位置监听器
        locationClient.registerLocationListener(new BDLocationListener() {
            @Override
            public void onReceiveLocation(BDLocation location) {
                // TODO Auto-generated method stub
                if (location == null || LOCATION_COUTNS>=1) {
                    return;
                }
                LOCATION_COUTNS ++;
                gps = location.getLatitude() + "," + location.getLongitude();


            }

            @Override
            public void onReceivePoi(BDLocation bdLocation) {

            }
        });
        locationClient.start();
        locationClient.requestLocation();
    }
    private class JsToJava{
        //这里需要加@JavascriptInterface，4.2之后提供给javascript调用的函数必须带有@JavascriptInterface
        @JavascriptInterface
        public void jsMethod(String paramFromJS){

        }
    }
    @Override
    protected void onStart() {
        super.onStart();
        String[] coordinate =getGps().split(",");
        Double lat = Double.parseDouble(coordinate[0]);
        Double lon = Double.parseDouble(coordinate[1]);

        if(checkLocation(lat,lon)) {
            postFaceCheckResult(host, cwrNo, 0,false,getGps(),1);
        } else {
            dialogForGPS();
        }
    }

    public String getJ(){
        SharedPreferences sp = getSharedPreferences("sp_setting", 0);
        return sp.getString("y", "");
    }

    public String getGps(){
        SharedPreferences sp = getSharedPreferences("sp_setting", 0);
        return sp.getString("gps", "");
    }


    public String getW(){
        SharedPreferences sp = getSharedPreferences("sp_setting", 0);
        return sp.getString("x", "");
    }

    public String getacceptRange(){
        SharedPreferences sp = getSharedPreferences("sp_setting", 0);
        return sp.getString("acceptRange", "");
    }

    public double distanceByLongNLat(double long1, double lat1, double long2, double lat2) {
        double a, b, R;
        R = 6371229;//地球半径
        lat1 = lat1 * Math.PI / 180.0;
        lat2 = lat2 * Math.PI / 180.0;
        a = lat1 - lat2;
        b = (long1 - long2) * Math.PI / 180.0;
        double d;
        double sa2, sb2;
        sa2 = Math.sin(a / 2.0);
        sb2 = Math.sin(b / 2.0);
        d = 2 * R * Math.asin(Math.sqrt(sa2 * sa2 + Math.cos(lat1) * Math.cos(lat2) * sb2 * sb2));
        return d;
    }

    public boolean checkLocation(double latitude, double longitude) {
        double range = Double.parseDouble(getacceptRange()) ;
        double j = Double.parseDouble(getJ());
        double w = Double.parseDouble(getW());

        double distance = distanceByLongNLat(latitude,longitude,j,w);

        return range - distance >=0;
    }

    private void dialogForGPS() {
        new AlertDialog.Builder(this).setTitle("GPS定位")
                .setMessage("您不在當前的工作區域，打卡失敗")
                .setPositiveButton("確定", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                        postFaceCheckResult(host, cwrNo, 0,false,gps,0);
                       // finish();
                    }
                }).create().show();
    }
}
